#!/usr/bin/perl 
#
#Check HOME
# Este script fara um check na home, verificando integridade de links de diversas urls da home. 

use strict ;
use IO::Socket;
use File::Basename;
use Sys::Hostname;
use WWW::Mechanize ;


my $remote_host = "www.uol.com.br";
my $remote_port = 80 ;

my $logDate = `/bin/date +%Y%m%d`;
chomp $logDate ;

my $errorLog = "/export/logs/check/monit_home-${logDate}.log";


my $hostname .= "check_home.adm.uol.intranet";
my $scriptname=basename("$0");

my %urls = ();
my %timeouts = ();

my $statusOK = 0;
my $statusWarning = 1;
my $statusCritical = 2;

sub timestamp
{
    my $tstamp = "[". time()."]";

    return ( $tstamp );
}

sub checkOldProcess ()
{
   my $myself = $0 ;

   my $mypid = $$ ;

   my $myppid = getppid(); 

   my @output = `ps -ef | grep $myself |egrep -v \"$mypid|$myppid\" |grep -v grep`; 

   #print "$myself $mypid $myppid\n";
 

   foreach my $line ( @output )
   {
       #print "$line\n"; 
       my ($f1, $pid, @rest ) = split ( /[\s|\t]+/ , $line );
       next if $pid == "" ; 
       #print "$pid\n"; 
       my $out = `kill $pid`; 
   }

}

sub printResult ()
{
   my $msg = shift();
  
   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full HOME;$msg";

   my $out = `/bin/logger -p local5.info \"$message\"`;

   open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   print  ERRORLOG "$message\n";
   close ( ERRORLOG );

   #print "$message\n";
}

sub abortResult ()
{
   my $msg = shift();

   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full HOME;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   #open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   #print  ERRORLOG "$message";
   #close ( ERRORLOG );

   print "$message\n";
   die "$message\n";
}



#my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,                                
                                               ##PeerPort => $remote_port,                                
					       #Proto    => "tcp",                                
					       #Type     => SOCK_STREAM)    
      #or &abortResult("$statusCritical;Couldn't connect to $remote_host:$remote_port : $@");
      #
#print $socket "GET /index.htm HTTP/1.0\nHOST: www.uol.com.br\n\n";

&checkOldProcess  ;

my $mech = WWW::Mechanize->new();

$mech->get("http://www.uol.com.br");

my @links =  $mech->find_all_links();


foreach my $link (@links )
{
   my $url = $link->url() ; 
   my $url_text = "[". $link->text() ."]";
   chomp $url ;
 
   if ( $url !~  /^http/ )
   {
       $url = "http://$url";
   }
 

   #if ( $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)[\"|\s|\>|\|\n]{1}/ )
   if ( $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)/ )
   {
       $url = $1;

       next if ( $url !~ /http:\/\/[\w|\d|\-]+\.[\w|\d|\-]+\..*/ );

       if ( $url =~ /(http:\/\/.*)\|http:\/\// )
       {
             $url = $1 ;
       }

       if ( $url !~  /clicklogger\.rm/ and $url !~ /^https/ )
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = $url_text ;
	  }
          else 
          {
               $urls{$url} .= $url_text ;
          }
       }
    }

    if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ )
    {
       #print "URL $url\n";
       if ( ! exists $urls{$url} )
       {
            $urls{$url} = $url_text ;
       }
       else 
       {
            $urls{$url} .= $url_text ;
       }
    }
    elsif ( $url =~ /href\=(http\:[\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1 ;
       if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/ and $url !~ /mixbrasil\.uol\.com\.br/)
       #if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/)
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = $url_text ;
	  }
          else 
          {
               $urls{$url} .= $url_text ;
          }
       }
    }
}

my $isOk = 0; 
my $failMessage = "";

## Alterado (20080730)
my $uri; my $hostname;

foreach my $url (keys %urls )
{
## Alterado (20080730)
   #$url =~ /http\:\/\/([\w|\-|\_|\.]+)(\/.*)/ ;
   #my $hostname = $1 ;
   #my $uri = $2 ;
   # ARAME:
   next if $url =~/polls.folha.com.br/;
   next if $url =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=/ ;
   next if $url =~ /http:\/\/\#/ ;
   next if $url =~/www2.uol.com.br/;
   next if $url =~/jogos360.uol.com.br/;
   #print "URL $url [$urls{$url}]\n";
   if ($url =~ /http\:\/\/([\w|\-|\_|\.]+)(\/.*)/){
	$hostname = $1 ;
	$uri = $2 ;
   } else {next}


   next if ( exists ($timeouts{$hostname}) );

   if ( $uri =~ /(.*)\|/ )
   {
       $uri = $1 ;
   }

   my $remote_host = $hostname;
   my $remote_port = 80 ;

   my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,
                                                  PeerPort => $remote_port,
						  Proto    => "tcp",
						  Type     => SOCK_STREAM,
						  Timeout => 40 )
   or my $failure  =  "$@"; 
   
   if ( $failure  )
   {
      if ( ! exists ($timeouts{$hostname}) )  
      {
          $timeouts{$hostname} = 1 ;
          $isOk = 1;
          $failMessage .= "( Error Connecting to $hostname $failure )" ; 
      }
      next ;
   }

   #if ( $hostname =~ /mixbrasil.uol.com.br/ || $hostname =~ /portalimprensa\.uol\.com\.br/ || $hostname =~ /www1\.uol\.com\.br/ || $hostname =~ /carsale\.uol\.com\.br/ || $hostname =~ /www2\.uol\.com\.br/)
   if ( $hostname =~ /mixbrasil.uol.com.br/ || $hostname =~ /portalimprensa\.uol\.com\.br/ || $hostname =~ /www1\.uol\.com\.br/ || $hostname =~ /carsale\.uol\.com\.br/ || $hostname =~ /shopping.uol.com.br/ || $hostname =~ /bbel.uol.com.br/  || $hostname =~ /jogos360.uol.com.br/ )
   {
        print $socket "GET $uri HTTP/1.1\nUser-Agent: checkHome\nHOST: $hostname\n\n";
   }
   else
   {
        print $socket "HEAD $uri HTTP/1.1\nUser-Agent: checkHome\nHOST: $hostname\n\n";
        print $socket "\n";
   }

   my $redirect = 0 ;

   while ( <$socket> )
   {
      my $response = $_ ;
      #print "$response\n";
      if ( $response =~ /HTTP\/1.1 200 OK/ )
      {
        #&printResult( "OK hostname \"$hostname$uri\"");
	last ;
      }
      #elsif ( $response =~ /HTTP\/1.1 30[1|2|7]\s/ )
      elsif ( $response =~ /HTTP\/1.1 30[1|2|7]\s/ )
      {
         $redirect = 1 ;
	 #print "REDIRECT\n$response\n";
      }
      elsif ( $response =~ /HTTP\/1.1 (\d+)\s/ )
      {
          my $code = $1 ;
          $isOk = 1;
          $failMessage .= "( HTTP ERROR CODE $code for host:  ${hostname}$uri  - $urls{$url} )" ; 
      }

      if ( $redirect == 1 and $response =~ /Location: (.*)/ )
      {
         my $location = $1 ;
	 if ( $location =~ /e.busca.uol.com.br/ )
	 {
            $isOk = 1;
            $failMessage .= "( HTTP ERROR CODE 302 for host: ${hostname}$uri - $location  - $urls{$url})" ; 
	 }
	 last ;
      }
   }
   close($socket);
}

if ( $isOk == 0 )
{
   &printResult ("$statusOK; Everything is fine");
}
else
{
   &printResult ( "$statusCritical;$failMessage" );
}
